package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.entity.ApArticle;
import com.heima.article.es.ApArticleSearch;
import com.heima.article.es.ApArticleSearchRepository;
import com.heima.article.service.IApArticleService;
import com.heima.article.service.ITemplateService;
import com.heima.common.minio.MinIOService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Service
public class TemplateServiceImpl implements ITemplateService {

    // 注入freemarker配置
    @Autowired
    private Configuration configuration;

    @Autowired
    private MinIOService minIOService;

    @Autowired
    private IApArticleService articleService;

    @Async
    @Override
    public void createHtml(ApArticle article, String content) {
        try {
            System.out.println(Thread.currentThread().getName() + "生成静态html服务开始执行");
            // 根据配置找到对应的模板
            Template template = configuration.getTemplate("article.ftl");
            // 封装数据
            Map<String, Object> map = new HashMap<>();
            map.put("content", JSON.parseArray(content));
            // 合并模板和数据
            StringWriter out = new StringWriter();
            template.process(map, out);
            // 上传静态html文件到minio
            InputStream is = new ByteArrayInputStream(out.toString().getBytes());
            String url = minIOService.upload(article.getId() + ".html", is, "text/html");
            // 将url地址更新到文章表中
            article.setStaticUrl(url);
            articleService.updateById(article);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Autowired
    private ApArticleSearchRepository articleSearchRepository;

    @Override
    @Async
    public void syncToEs(ApArticle article) {
        System.out.println(Thread.currentThread().getName() + "同步es服务开始执行");
        ApArticleSearch search = new ApArticleSearch();
        BeanUtils.copyProperties(article, search);
        articleSearchRepository.save(search);
    }
}
